import dns.resolver
import logging
logger = logging.getLogger("fast-run")

class DNSUtil:

    @classmethod
    def has_cname(cls, domain, expected_cname=None):
        """
        测试域名是否存在指定的 CNAME 记录
        :param domain: 要测试的域名
        :param expected_cname: 期望的 cname 目标（比如 'example.target.com.'）
        :return: True/False
        """
        logger.info(f"检测：{domain}  CNAME   {expected_cname}")
        try:
            answers = dns.resolver.resolve(domain, 'CNAME')
            for rdata in answers:
                cname_target = str(rdata.target).rstrip('.')  # 去掉末尾的点
                print(f"{domain} -> {cname_target}")
                if expected_cname:
                    # 比对是否等于预期 cname
                    if cname_target.lower() == expected_cname.rstrip('.').lower():
                        return True
                    else:
                        return False
            return True if not expected_cname else False
        except dns.resolver.NoAnswer:
            return False
        except dns.resolver.NXDOMAIN:
            print(f"域名不存在: {domain}")
            return False
        except dns.exception.Timeout:
            print(f"查询超时: {domain}")
            return False
        except Exception as e:
            print(f"查询失败: {e}")
            return False


    @classmethod
    def verify_domain(cls, domain:str, hosts:list):
        """
            检查指定域名是否有对应的主机 A 记录

            Args:
                domain: 要检查的域名
                host: 预期的主机名

            Returns:
                bool: 如果找到匹配的 A 记录返回 True，否则返回 False
            """
        try:
            # 解析域名的 A 记录
            answers = dns.resolver.resolve(domain, 'A')

            # 获取所有 IP 地址
            domain_ips = {str(rdata) for rdata in answers}
            host_ips = {host for host in hosts}

            logger.info(f"解析出domain 对应IP {domain_ips}")
            logger.info(f"需要包含的IP： {host_ips}")

            # 检查是否有交集
            return len(domain_ips & host_ips) > 0

        except dns.resolver.NXDOMAIN:
            logger.error(f"{domain} 域名不存在")
            return False
        except dns.resolver.NoAnswer:
            # 没有 A 记录
            return False
        except Exception as e:
            # 其他 DNS 错误
            print(f"DNS 查询错误: {e}")
            return False


if __name__ == '__main__':
    print(DNSUtil.has_cname("hello.catpd.cn", "target.example.net"))